package com.moyq5.wifi.joystick.worker.netty.handler;

import com.moyq5.wifi.joystick.Console;
import com.moyq5.wifi.joystick.ConsoleFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class DiscardClientHandler extends ChannelInboundHandlerAdapter {
    private static final Console console = ConsoleFactory.get(DiscardClientHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        console.info("服务已连接：%s", ctx.channel().remoteAddress().toString());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        console.info("服务已断开：%s", ctx.channel().remoteAddress().toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
        // Discard the received data silently.
        ByteBuf buf = (ByteBuf) msg;
        console.info("收到数据：%s", ByteBufUtil.hexDump(buf));
        buf.release(); // (3)
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection when an exception is raised.
        console.error(cause, "数据异常");
        cause.printStackTrace();
        ctx.close();
    }
}
